package com.ybl.store.common.util;

import com.alibaba.fastjson2.JSON;
import com.ybl.store.backend.dto.UserInfoDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 工具类
 */
@Slf4j
public class JwtUtil {

    private static final String SUBJECT_KEY_USER_INFO = "SUBJECT_KEY_USER_INFO";
    private static final String ISS = "ybl-store";
    private static final long EXPIRATION = 14400;

    /**
     * 创建 jwt 令牌
     *
     * @param secretKey 密钥
     * @param userInfoDTO 用户信息
     * @return jwt 令牌
     */
    public static String createJwtToken(String secretKey, UserInfoDTO userInfoDTO) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(SUBJECT_KEY_USER_INFO, JSON.toJSONString(userInfoDTO));

        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .setIssuedAt(new Date())
                .setIssuer(ISS)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
    }

    /**
     * 解析 jwt 令牌
     *
     * @param secretKey 密钥
     * @param jwtToken jwt 令牌
     * @return 解析成功： UserInfoDTO 解析失败：null
     */
    public static UserInfoDTO parseJwtToken(String secretKey, String jwtToken) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken).getBody();
            String userInfoStr = claims.get(SUBJECT_KEY_USER_INFO).toString();

            return JSON.parseObject(userInfoStr, UserInfoDTO.class);
        } catch (Exception ignore) {
            return null;
        }
    }
}
